import {defineStore} from "pinia";
import {formatDate} from "@/utils/timeUtils.js";

export const useMessageStore = defineStore('useMessageStore', {
    state() {
        return {
            historyList: [],//聊天列表
            chatDetails: {},//聊天详情
            activeFUuid: "",//当前选择的uuid
            sendFun: null,//发送websocket消息的方法
            newMsgStatus: null,//新消息状态，值改变时说明有了新消息
        }
    },
    getters: {
        //获取聊天历史列表
        getHistoryList(state) {
            return state.historyList
        },

        //获取聊天信息，根据好友uuid
        getHistoryItem(state) {
            return function (fUuid) {
                //找到当前的聊天记录
                let obj = null;
                let index, len = this.historyList.length;
                for (index = 0; index < len; index++) {
                    let item = this.historyList[index];
                    if (item.f_uuid === fUuid) {
                        obj = item;
                        break;
                    }
                }
                return {obj, index};
            }
        },

        //获取聊天详情列表
        getHistoryDetails(state) {
            return state.chatDetails;
        },

        //获取当前正在聊天的uuid
        getActiveFUuid: (state) => {
            return state.activeFUuid;
        },

        //根据fUuid获取聊天信息
        getDetailByFUuid(state) {
            return (fUuid) => {
                let list = this.historyList;
                for (let i in list) {
                    if (list[i].f_uuid === fUuid) {
                        return list[i];
                    }
                }

                return null;
            }
        },

        getDetailsDef: state => {
            return {
                loading: false,
                LoadAll: false,//加载完毕状态
                list: []
            }
        }
    },
    actions: {
        //设置发送消息方法
        setSendFunc(func) {
            this.sendFun = func;
        },

        //设置聊天列表
        setHistoryList() {
            console.log(123);
            //组织发送的消息
            let message = {
                "type": "messageHistory",
                "content": ""
            }
            this.sendFun(JSON.stringify(message));
        },

        //设置聊天详情
        setHistoryDetails(fUuid) {
            let item = this.getHistoryDetails[fUuid];
            if (!item) {
                return;
            }

            //组织发送的消息
            let obj = {
                f_uuid: fUuid,
                load_size: item.list.length
            };
            let message = {
                "type": "messageDetails",
                "content": JSON.stringify(obj)
            }
            this.sendFun(JSON.stringify(message));
        },

        //设置当前聊天的uuid
        setActiveFUuid(fUuid) {

            if (this.activeFUuid == fUuid) {
                //当前已经选中此聊天记录
                return;
            }

            this.activeFUuid = fUuid;
            const obj = this.getHistoryDetails[fUuid];
            if (!obj.list.length) {
                this.setHistoryDetails(fUuid);
            }

            //清除未读消息数量
            let item = this.getDetailByFUuid(fUuid);
            if (!item) {
                return;
            }
            if (item.unread_num) {
                this.addHistoryUnreadNum(fUuid, -1);
                this.cleanHistoryUnread(fUuid);
            }
        },

        /**
         * 添加聊天列表
         * @param obj
         */
        addHistory(obj) {
            this.historyList.unshift(obj);
            this.chatDetails[obj.f_uuid] = this.getDetailsDef;
        },

        /**
         * 增加聊天未读消息
         * @param fUuid
         * @param num
         */
        addHistoryUnreadNum(fUuid, num) {
            let item = this.getDetailByFUuid(fUuid);
            if (!item) {
                return;
            }
            if (num < 1) {
                item.unread_num = 0;
            } else {
                item.unread_num += num;
            }
        },

        /**
         * 修改聊天预览消息
         * @param fUuid
         * @param msg
         */
        changeHistoryMsgView(fUuid, msg) {
            let obj = this.getDetailByFUuid(fUuid);
            if (!obj) {
                return;
            }
            obj.msg_view = msg;
            obj.created_at = formatDate('Y/m/d/H/i/s');
        },

        /**
         * 添加聊天消息
         * @param fUuid
         * @param msg
         */
        addHistoryMsg(fUuid, msg) {
            // {
            //     created_at: "2025-10-16T23:05:33+08:00",
            //         from_uid: userInfoStore.getUserInfo.value.uuid,
            //     msg_content: obj.msg_content,
            //     msg_type: "text",
            //     to_uid: obj.to_uid
            // }
            this.chatDetails[fUuid].list.push(msg);
            this.chatDetails[fUuid].total++;
            //添加新消息状态，外部可以监听这个状态，来自定滚动滚动条
            this.newMsgStatus = (new Date).getTime();
        },

        /**
         * 清除聊天记录的未读消息
         * @param fUuid
         */
        cleanHistoryUnread(fUuid) {
            //组织发送的消息
            let obj = {
                uuid: fUuid,
            };
            let message = {
                "type": "cleanUnread",
                "content": JSON.stringify(obj)
            }
            this.sendFun(JSON.stringify(message));
        },


        /**
         * 处理聊天消息
         * @param msg
         */
        handleChatMsg(msg) {
            const content = JSON.parse(msg);
            //获取当前正在聊天的fUuid
            const fUuid = messageStore.getActiveFUuid;
            // 当前的fUuid等于发送消息的fUuid时，直接将消息加入到聊天列表
            if (fUuid === content.from_uid) {
                messageStore.addHistoryMsg(content.from_uid, content);
                //修改聊天预览消息
                messageStore.changeHistoryMsgView(content.from_uid, content.msg_content);
                //清除未读消息
                messageStore.cleanHistoryUnread(fUuid)
                return;
            }

            //当前from_uuid是否存在聊天列表，不存在时创建聊天列表
            const chatList = messageStore.getHistoryDetails;
            if (!chatList.hasOwnProperty(content.from_uid)) {
                //添加聊天列表
                messageStore.addHistory({
                    created_at: formatDate('Y/m/d/H/i/s'),
                    f_uuid: content.from_uid,
                    msg_view: content.msg_content,
                    unread_num: 1
                });
                return;
            }

            //增加未读消息数量
            messageStore.addHistoryUnreadNum(content.from_uid, 1);
            //修改聊天预览消息
            messageStore.changeHistoryMsgView(content.from_uid, content.msg_content);

            //当断from_uid的聊天是否加载过详情数据，加载过时，将当前消息推送到聊天详情
            if (chatList[content.from_uid].page !== 1) {
                messageStore.addHistoryMsg(content.from_uid, content);
            }
        },

        /**
         * 处理聊天详情消息
         * @param msg
         */
        handleMessageDetails(msg) {
            const content = JSON.parse(msg);
            let list = content.list.reverse();

            let item = this.getHistoryDetails[content.f_uuid];
            const len = item.list.length;
            item.list = [...list, ...item.list];

            //发布新消息事件
            if (!len) {
                this.newMsgStatus = (new Date).getTime();
            }
        },

        /**
         * 聊天列表
         * @param msg
         */
        handleMessageHistory(msg) {
            const list = JSON.parse(msg);
            for (let i in list) {
                let obj = list[i];
                this.chatDetails[obj.f_uuid] = this.getDetailsDef;
            }
            this.historyList = list;
        }
    }
});